﻿using DICOMViewer.Utility;
using IncoolDicomViewerBase;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using xDataSet;

namespace IncoolReg
{
    public partial class MainForm : Form
    {
        public static Hashtable G_BLL_Object;
        protected string mMainURL = "3dmed.net";
        protected string mAppID = "";
        protected string mDepId = "";
        protected string mDepName = "";
        protected string mProvinceId = "";
        protected string mProvinceName = "";
        protected string mCityId = "";
        protected string mCityName = "";
        protected string mAreaId = "";
        protected string mAreaName = "";
        protected string mZuzhiId = "";
        protected string mZuzhiName = "";
        protected string mDepartmentId = "";
        protected string mDepartmentName = "";
        protected string mOfficeId = "";
        protected string mOfficeName = "";
        protected string mHospitailId = "";
        protected string mHospitailName = "";

        protected string mMacAddress = string.Empty;

        public MainForm()
        {
            InitializeComponent();
            G_BLL_Object = new Hashtable();
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            txt_sn.Text = HardWareUtility.GetHardwareCode();
            form_init();
        }

        protected string dataXmlSavePathFormat = Application.StartupPath + "\\ld\\{0}";
        protected Task getDataTask;
        protected readonly string offlineDataSavePath = OfflineUtility.OfflineDataSavePathFormat;

        protected void SaveJsonFile(string contentStr, string fileName)
        {
            string savePath = string.Format(dataXmlSavePathFormat, fileName);
            if (File.Exists(savePath))
            {
                File.Copy(savePath, savePath + ".bak", true);
                File.Delete(savePath);
            }
            try
            {
                using (FileStream stream = File.Open(savePath, FileMode.Create))
                {
                    StreamWriter sw = new StreamWriter(stream);
                    sw.Write(contentStr);
                    sw.Flush();
                    sw.Close();
                    stream.Close();
                }
            }
            catch (Exception e)
            {
                string bakPath = savePath.Replace(".bak", string.Empty);
                if (File.Exists(bakPath))
                {
                    File.Copy(bakPath, savePath, true);
                }
                throw e;
            }
        }

        #region 虚函数集，供子类实现、重写

        protected virtual void form_init()
        {
        }

        protected virtual List<Hashtable> GetDepartmentData()
        {
            throw new NotImplementedException("Method GetDepartmentData Not Implemented!");
        }

        protected virtual void InitDepartmentControl(List<Hashtable> mRetList)
        {
            cmb_dep.Items.Clear();
            cmb_dep.DisplayMember = "name";
            cmb_dep.ValueMember = "id";
            for (int i = 0; i < mRetList.Count; i++)
            {
                //添加每一条数据
                cmb_dep.Items.Add(new {id = mRetList[i]["id"].ToString(), name = mRetList[i]["name"]});
            }
        }

        protected virtual List<Hashtable> GetProvinceData()
        {
            throw new NotImplementedException("Method GetProvinceData Not Implemented!");
        }

        protected virtual void InitProvinceControl(List<Hashtable> provinceList)
        {
            cmb_zhuzi.DisplayMember = "aname";
            cmb_zhuzi.ValueMember = "id";
            for (int i = 0; i < provinceList.Count; i++)
            {
                //添加每一条数据
                cmb_zhuzi.Items.Add(new
                {
                    uuid = provinceList[i]["uuid"].ToString(),
                    aname = provinceList[i]["aname"],
                    id = provinceList[i]["id"].ToString(),
                    zipCode = provinceList[i]["zipCode"],
                    areaId = provinceList[i]["areaId"].ToString(),
                    areaName = provinceList[i]["areaName"],
                    provinceId = provinceList[i]["provinceId"].ToString(),
                    provinceName = provinceList[i]["provinceName"],
                    cityName = provinceList[i]["cityName"],
                    cityId = provinceList[i]["cityId"].ToString()
                });
            }
        }

        protected virtual List<Hashtable> GetOfficeDataByHospital(string hospitaluuid)
        {
            throw new NotImplementedException("Method GetProvinceData Not Implemented!");
        }

        protected virtual void InitOfficeControl(List<Hashtable> mRetList)
        {
            cmb_office.Items.Clear();
            cmb_office.DisplayMember = "title";
            cmb_office.ValueMember = "id";
            for (int i = 0; i < mRetList.Count; i++)
            {
                //添加每一条数据
                cmb_office.Items.Add(new {id = mRetList[i]["id"].ToString(), title = mRetList[i]["title"]});
            }
        }

        #endregion

        private void cb_ok_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_name.Text.Trim()) ||
                string.IsNullOrEmpty(mProvinceId) ||
                string.IsNullOrEmpty(mHospitailId) ||
                string.IsNullOrEmpty(mOfficeId) ||
                string.IsNullOrEmpty(mDepartmentId))
            {
                MessageBox.Show("数据填写不全！请补全！");
                return;
            }
            //数据保存
            if (SaveEquipmentData()) PerformSaveSuccess();
        }

        protected virtual bool SaveEquipmentData()
        {
            throw new NotImplementedException("Method SaveEquipmentData Not Implemented!");
        }

        private void PerformSaveSuccess()
        {
            MessageBox.Show("保存成功");
            txt_name.Enabled = false;
            cmb_zhuzi.Enabled = false;
            cmb_hospital.Enabled = false;
            cmb_dep.Enabled = false;
            cmb_office.Enabled = false;
            cmb_province.Enabled = false;
            cmb_city.Enabled = false;
            cmb_area.Enabled = false;
            cb_ok.Visible = false;
        }

        private void cmb_zhuzi_SelectedIndexChanged(object sender, EventArgs e)
        {
            //获取所属医院信息
            //MessageBox.Show(  ((List<Hashtable>)cmb_zhuzi.SelectedItem).ToString() );
            cmb_hospital.Items.Clear();
            cmb_hospital.Text = "";
            cmb_office.Items.Clear();
            cmb_office.Text = "";

            dynamic obj = cmb_zhuzi.SelectedItem;
            var name = obj.aname;
            var companyUuid = obj.uuid;
            mZuzhiId = obj.id;
            mZuzhiName = (string) obj.aname;
            mCityId = (string) obj.cityId;
            mCityName = (string) obj.cityName;
            mProvinceId = (string) obj.provinceId;
            mProvinceName = (string) obj.provinceName;
            mAreaId = (string) obj.areaId;
            mAreaName = (string) obj.areaName;

            cmb_province.Text = mProvinceName;
            cmb_city.Text = mCityName;
            cmb_area.Text = mAreaName;

            //uuid = provinceList[i]["uuid"],
            //aname = provinceList[i]["aname"],
            //id = provinceList[i]["id"],
            //zipCode = provinceList[i]["zipCode"],
            //areaId = provinceList[i]["areaId"],
            //areaName = provinceList[i]["areaName"],
            //provinceId = provinceList[i]["provinceId"],
            //provinceName = provinceList[i]["provinceName"],
            //cityName = provinceList[i]["cityName"],
            //cityId = provinceList[i]["cityId"]
            //处理参数

            List<Hashtable> hospitalList = GetHospitalDataByCompanyUuid(companyUuid);

            if (hospitalList != null) InitHospitalControl(hospitalList);
        }

        protected virtual List<Hashtable> GetHospitalDataByCompanyUuid(string companyUuid)
        {
            throw new NotImplementedException("Method GetProvinceData Not Implemented!");
        }

        protected virtual void InitHospitalControl(List<Hashtable> hospitalList)
        {
            cmb_hospital.Items.Clear();
            cmb_hospital.DisplayMember = "title";
            cmb_hospital.ValueMember = "id";
            for (int i = 0; i < hospitalList.Count; i++)
            {
                //添加每一条数据
                cmb_hospital.Items.Add(
                    new
                    {
                        id = hospitalList[i]["id"].ToString(),
                        uuid = hospitalList[i]["uuid"],
                        title = hospitalList[i]["title"],
                        provinceId = hospitalList[i]["provinceId"],
                        provinceName = hospitalList[i]["provinceName"],
                        cityId = hospitalList[i]["cityId"],
                        cityName = hospitalList[i]["cityName"],
                        areaId = hospitalList[i]["areaId"],
                        areaName = hospitalList[i]["areaName"]
                    });
            }
        }

        private void cmb_hospital_SelectedIndexChanged(object sender, EventArgs e)
        {
            //cmb_office
            dynamic hospital = cmb_hospital.SelectedItem;
            var name = hospital.title;
            var mId = hospital.uuid;

            //处理选中的医院
            mHospitailId = hospital.id;
            mHospitailName = hospital.title;

            //处理省市区选项
            mProvinceId = hospital.provinceId?.ToString();
            cmb_province.Text = hospital.provinceName?.ToString();
            mCityId = hospital.cityId?.ToString();
            cmb_city.Text = hospital.cityName?.ToString();
            mAreaId = hospital.areaId?.ToString();
            cmb_area.Text = hospital.areaName?.ToString();

            //获取医院下科室信息
            List<Hashtable> officeList = GetOfficeDataByHospital(mId);
            //初始化科室下拉菜单
            if (officeList != null) InitOfficeControl(officeList);
        }

        private void cb_exit_Click(object sender, EventArgs e)
        {
#if DEBUG
            while (true)
            {
                if (getDataTask == null || getDataTask.IsCompleted) break;
                Thread.Sleep(100);
            }
#endif
            this.Close();
            Application.Exit();
        }

        private void cmb_dep_SelectedIndexChanged(object sender, EventArgs e)
        {
            //处理部门类型数据
            dynamic obj = cmb_dep.SelectedItem;

            //处理选中的医院
            mDepartmentId = obj.id;
            mDepartmentName = obj.name;
        }

        private void cmb_office_SelectedIndexChanged(object sender, EventArgs e)
        {
            //处理科室类型数据
            dynamic obj = cmb_office.SelectedItem;

            //处理选中的医院
            mOfficeId = obj.id;
            mOfficeName = obj.title;
        }
    }
}